package com.leeassamite.util;

import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.ywh.train.Config;
import com.ywh.train.Constants;

/**
 * 邮件发送类
 * 
 * @author leeassamite
 * 
 */
public class MailSender {

	/** email的字符集 */
	private final static String email_charset = "UTF-8";;
	
	private static Properties mailProps;
	static{
		mailProps = new Properties();
		// 创建发信服务器
		mailProps.put("mail.smtp.auth", "true");
		mailProps.put("mail.transport.protocol", "smtp");
		
		
		mailProps.put("mail.smtp.host", Config.getProperty("email.smtp.host"));
		mailProps.put("mail.smtp.port", Config.getProperty("email.smtp.port"));
		Boolean starttls = "1".equals(Config.getProperty("email.starttls"));
		mailProps.put("mail.smtp.starttls.enable",starttls?"true":"false");
		mailProps.put("mail.smtp.auth", "true");
		mailProps.put("mail.smtp.debug", "true");
		
		if("1".equals(Config.getProperty("email.ssl"))){
			Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
			final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
			mailProps.put("mail.smtp.socketFactory.class", SSL_FACTORY);
			mailProps.put("mail.smtp.socketFactory.fallback", "false");
			mailProps.put("mail.smtp.socketFactory.port", Config.getProperty("email.smtp.port"));
		}
	}
	
	
	/**
	 * 发送文本邮件
	 * @param toMail 目标邮箱
	 * @param subject 邮件主题
	 * @param content 邮件内容
	 * @throws MessagingException 
	 * @throws UnsupportedEncodingException 
	 */
	public static void sendTextMail(String toMail,
			String subject, String content) throws UnsupportedEncodingException, MessagingException {
		// 设置目标邮箱
		String targetEmail = toMail;
		// 设置发送内容
		String encode_content = content;
		
		final String fromUser = Config.getProperty("email.user");
		final String pwd = Config.getProperty("email.pwd");
		
		MimeMessage msg = getMimeMessage(fromUser, pwd);
		
		
		// 设置发信人地址
		msg.setFrom(new InternetAddress(fromUser, Constants.EMAIL_NAME ,email_charset));
		// 设置收信人
		msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(targetEmail));
		// 设置发送日期
		msg.setSentDate(new Date());
		// 设置邮件主题
		msg.setSubject(subject,email_charset);
		// 设置邮件正文
		msg.setText(encode_content,email_charset);
		Transport.send(msg);
	}
	
	/**
	 * 发送HTML邮件
	 * @param toMail 目标邮箱
	 * @param subject 邮件主题
	 * @param body 邮件内容(HTML)
	 * @throws UnsupportedEncodingException
	 * @throws MessagingException
	 */
	public static void sendHtmlMail(String toMail,
			String subject, String body) throws UnsupportedEncodingException, MessagingException{
		// 设置目标邮箱
		String targetEmail = toMail;
		// 设置发送内容
		String encode_content = body;
		
		final String fromUser = Config.getProperty("email.user");
		final String pwd = Config.getProperty("email.pwd");
		
		MimeMessage msg = getMimeMessage(fromUser, pwd);
		
		// 设置发信人地址
		msg.setFrom(new InternetAddress(fromUser, Constants.EMAIL_NAME ,email_charset));
		// 设置收信人
		msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(targetEmail));
		// 设置发送日期
		msg.setSentDate(new Date());
		// 设置邮件主题
		msg.setSubject(subject,email_charset);

		// 设置邮件正文
		// MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象
		Multipart mainPart = new MimeMultipart();
		// 创建一个包含HTML内容的MimeBodyPart
		BodyPart html = new MimeBodyPart();
		// 设置HTML内容
		html.setContent(encode_content, "text/html; charset=utf-8");
		mainPart.addBodyPart(html);
		// 将MiniMultipart对象设置为邮件内容
		msg.setContent(mainPart);
		
		Transport.send(msg);
	}

	
	private static MimeMessage getMimeMessage(final String username,final String userpwd){
		// 得到默认的对话对象
		Authenticator authenticator = new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, userpwd);
			}
		};
		
		// 创建Session实例
		Session session = Session.getDefaultInstance(mailProps, authenticator);
		// 创建MimeMessage实例对象
		return new MimeMessage(session);
	}
	
	
	public static void main(String[] args){
		try {
			
			String to = Config.getProperty("email.target");
			
			String content = "我是内容<BR />asdff生生世世是";
			String title = "测试中文呗";
			
			sendTextMail(to,title,content);
			
			sendHtmlMail(to,title,content);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}
